import axios from 'axios';
import { message } from 'ant-design-vue';
import { i18nRender } from '@/locales';
import { LocalUtil } from '@utils/index';

function request(url, method, params = {}, config = {}) {
  if (!method) {
    message.error(i18nRender('gatewayVlanConf.setRequestType'));
    return;
  }
  //默认系统参数
  let opts = {
    // timeout: 3000,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    },
  };
  Object.assign(opts, config);
  switch (method) {
    case 'GET':
      return new Promise((resolve, reject) => {
        axios
          .get(url, { params, ...opts })
          .then((response) => {
            resolve(response.data);
          })
          .catch((error) => {
            reject(error);
          });
      });
    case 'POST':
      return new Promise((resolve, reject) => {
        axios
          .post(url, params, opts)
          .then((response) => {
            resolve(response.data);
          })
          .catch((error) => {
            reject(error);
          });
      });
    case 'DELETE':
      return new Promise((resolve, reject) => {
        axios
          .delete(url, { params, ...opts })
          .then((response) => {
            resolve(response.data);
          })
          .catch((error) => {
            reject(error);
          });
      });
    case 'PUT':
      return new Promise((resolve, reject) => {
        axios
          .put(url, params, opts)
          .then((response) => {
            resolve(response.data);
          })
          .catch((error) => {
            reject(error);
          });
      });
    case 'PATCH':
      return new Promise((resolve, reject) => {
        axios
          .patch(url, params, opts)
          .then((response) => {
            resolve(response.data);
          })
          .catch((error) => {
            reject(error);
          });
      });
  }
}

/**
 * 
 * @DATA {
 *  api: url,
    method: method,
    params:{                       //post和put的body参数,get和delete请求不用传				
    }
    module: "default"  //api模块，用于区分service 部署的ip,不传默认default，非/service/api/的模块都需要传该参数，巡检--inspection，日志--logbiz，终端管理--pyservice 
 * @param {*} ops 
 * @param {*} proxyType 
 */
function requestHttp(data, ops = {}, proxyType = 'common') {
  try {
    if (!data) {
      message.error(i18nRender('gatewayVlanConf.setRequestParam'));
      return;
    }

    if (data && !data.api) {
      message.error(i18nRender('gatewayVlanConf.setRequestApiAddress'));
      console.trace('请填写请求api地址');
      return;
    }

    if (data && !data.method) {
      message.error(i18nRender('gatewayVlanConf.setRequestApiType'));
      return;
    }

    if (!data.module) {
      data.module = 'default';
    }
    if (data.replaces) {
      for (let [key, val] of Object.entries(data.replaces)) {
        data.api = data.api.replace(`{${key}}`, val);
      }
      Reflect.deleteProperty(data, 'replaces');
    }

    const url = encodeURI(
      `/webproxy/${proxyType}/api?${data.api.split('?')[0]}`
    );

    const locationParams = LocalUtil.parseQueryString();
    if (locationParams.debugger == 'true') {
      if (data.querys) {
        data.querys.debug = true;
      } else {
        data.querys = { debug: true };
      }
    }

    //console.log('url=========', url);
    const options = {
      method: 'POST',
      contentType: 'application/json',
      ...ops,
    };
    if (/\s/g.test(data.api)) {
      data.api = encodeURI(data.api);
    }
    //console.log(options);
    return new Promise((resolve, reject) => {
      axios
        .post(url, data, options)
        .then((response) => {
          if (response && response.data) {
            resolve(response.data);
          } else {
            reject({ msg: i18nRender('common.noReturn') });
          }
        })
        .catch((error) => {
          reject(error);
        });
    });
  } catch (err) {
    console.error(err);
  }
}
/**
 * 
 * @param data{
 *  method: 'GET',
*   module: 'default',
    api:xx
    fileName:"xx"
}  
 * @param {*} TYPE pdf/doc/zip/image
 * @returns 
 */
function requestHttpDownload(data, TYPE) {
  if (!data) {
    message.error(i18nRender('gatewayVlanConf.setRequestParam'));
    return;
  }
  let realData = '';
  //兼容原来的方法，原来data传入是完整的数据
  if (typeof data == 'object') {
    let contentType = 'application/pdf;charset=UTF-8';
    if (TYPE == 'zip') {
      contentType = 'application/x-zip-compressed;charset=UTF-8';
    } else if (TYPE == 'image') {
      contentType = 'application/image;charset=UTF-8';
    }
    let optsData = {
      method: 'GET',
      module: 'default', //api模块，用于区分service 部署的ip,不传默认default，非/service/api/的模块都需要传该参数，巡检--inspection，日志--logbiz，终端管理--pyservice
      contentType: contentType,
      attachment: true, //是否以附件形式下载，默认true
    };
    realData = JSON.stringify({ ...optsData, ...data });
  } else {
    realData = data;
  }

  const options = {
    method: 'POST',
    contentType: 'application/json',
  };
  const url = '/webproxy/common/file/download/submit';
  return new Promise((resolve, reject) => {
    axios
      .post(url, realData, options)
      .then((response) => {
        if (response && response.data) {
          resolve(response.data);
        } else {
          reject({ msg: i18nRender('common.noReturn') });
        }
      })
      .catch((error) => {
        reject(error);
      });
  });
}

function requestHttpUpload(data, uploadProgrss) {
  const url = '/webproxy/common/file/upload';
  var fd = new FormData();
  fd.append('file', data.file);
  fd.append('uploadData', data.uploadData);
  return new Promise((resolve, reject) => {
    axios
      .post(url, fd, uploadProgrss)
      .then((res) => {
        console.log(res);
        resolve(res.data);
      })
      .catch((error) => {
        reject(error);
      });
  });
}
function requestHttpUploadByForm(data, uploadProgrss) {
  const url = '/webproxy/common/file/upload_by_form';
  var fd = new FormData();
  fd.append('file', data.file);
  fd.append('uploadData', data.uploadData);
  return new Promise((resolve, reject) => {
    axios
      .post(url, fd, uploadProgrss)
      .then((res) => {
        console.log(res);
        resolve(res.data);
      })
      .catch((error) => {
        reject(error);
      });
  });
}

/**
 *
 * @param {*} data
 * {
 * api:'xxxx",
 * fileName:['filename1',"filename2"]  //导入文件名称和导入的数组files需要一一对应 传递给后端提供的接口
 * }
 * @param {*} apiData //传入的是后端接口需要的参数 {password:"xxxx"}
 * @returns
 */
function requestHttpUploadByFormList(data, apiData) {
  const options = {
    method: 'POST',
    mimeType: 'multipart/form-data',
    contentType: false,
  };
  const url = '/webproxy/common/file/upload_by_form_list';
  var fd = new FormData();
  data.files.forEach((file) => {
    fd.append('files', file);
  });

  fd.append('uploadData', data.uploadData);
  fd.append('apiData', JSON.stringify(apiData));
  return new Promise((resolve, reject) => {
    axios
      .post(url, fd, options)
      .then((res) => {
        console.log(res);
        resolve(res.data);
      })
      .catch((error) => {
        reject(error);
      });
  });
}

/**
 * 获取系统时间
 * @returns Promise
 */
function requestSystemTime() {
  const url = '/webproxy/common/sys/time';
  axios.get(url);
  //默认系统参数
  return new Promise((resolve, reject) => {
    axios
      .get(url)
      .then((response) => {
        if (response && response.data) {
          resolve(response.data);
        } else {
          reject({ msg: i18nRender('common.noReturn') });
        }
      })
      .catch((error) => {
        reject(error);
      });
  }).catch(() => {});
}

/**
 * 获取系统配置
 * @returns
 */
function requestSystemConf() {
  const url = '/webproxy/common/sys/params';
  //默认系统参数
  return new Promise((resolve, reject) => {
    axios
      .get(url)
      .then((response) => {
        if (response && response.data) {
          resolve(response.data);
        } else {
          reject({ msg: i18nRender('common.noReturn') });
        }
      })
      .catch((error) => {
        reject(error);
      });
  });
}

/**
 * JSONP方法
 * @param {*} param0
 */
function requestJsonp({ url, params = {}, success }) {
  // 根据时间戳生成一个callback名
  let callbackName = `jsonp_${new Date().getTime()}`;

  // 创建script
  let script = document.createElement('script');

  // 字符串拼接生成基本url
  let baseUrl = `${url}?callback=${callbackName}`;

  // 取出params对象属性并得到完整url
  for (let item in params) {
    baseUrl += `&${item}=${params[item]}`;
  }

  // jsonp核心，通过script的跨域特性发出请求
  script.src = baseUrl;

  // 把创建的script挂载到DOM
  document.body.appendChild(script);

  // 给window添加属性，用于获取jsonp结果
  window[callbackName] = (res) => {
    // 执行success回调
    success(res);
    // 删除window下属性
    delete window[callbackName];
    // 得到结果后删除创建的script
    document.body.removeChild(script);
  };
}

export {
  request,
  requestHttp,
  requestHttpDownload,
  requestJsonp,
  requestHttpUpload,
  requestHttpUploadByForm,
  requestHttpUploadByFormList,
  requestSystemTime,
  requestSystemConf,
};
